﻿using Demo.Model.Entitys;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Reflection;

namespace Demo.Api.Controllers.BasicData
{
    /// <summary>
    /// 数据库管理Tool
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ToolController : ControllerBase
    {
        private readonly ISqlSugarClient _db;
        private readonly ILogger<ToolController> _logger;
        public ToolController(ISqlSugarClient db, ILogger<ToolController> logger)
        {
            _db = db;
            _logger = logger;
            _logger.LogInformation($"{GetType().Name}被构造了");
        }
        /// <summary>
        /// 创建数据库及Model.Entitys实体表
        /// </summary>
        /// <returns></returns>
        [HttpGet]

        public string InitDataBase()
        {
            string aa = "ok";
            //只有不存在才会创建数据库
            _db.DbMaintenance.CreateDatabase();
            //创建表
            string paspace = "Demo.Model.Entitys";//获取类库的名称
            //通过反射读取我们想要的类(注意添加项目引用)
            Type[] ass = Assembly.LoadFrom(AppContext.BaseDirectory + "Demo.Model.dll").GetTypes().Where(p => p.Namespace.Contains(paspace)).ToArray();
            _db.CodeFirst.SetStringDefaultLength(200).InitTables(ass);
            //初始化炒鸡管理员和菜单
            Users user = new Users()
            {
                Name = "admin",
                NickName = "炒鸡管理员",
                Password = "123456",
                UserType = 0,
                IsEnable = true,
                Description = "数据库初始化时默认添加的炒鸡管理员",
                CreateDate = DateTime.Now,
                CreateUserId = 0,
                IsDeleted = 0
            };
            long userId = _db.Insertable(user).ExecuteReturnBigIdentity();
            Menu menuRoot = new Menu()
            {
                Name = "菜单管理",
                Index = "menumanager",
                FilePath = "../views/admin/menu/MenuManager",
                ParentId = 0,
                Order = 0,
                IsEnable = true,
                Description = "数据库初始化时默认添加的默认菜单",
                CreateDate = DateTime.Now,
                CreateUserId = userId,
                IsDeleted = 0
            };
            _db.Insertable(menuRoot).ExecuteReturnBigIdentity();
            return aa;
        }
        [HttpGet]
        public string log4net()
        {
            _logger.LogInformation($"{GetType().Name}被执行了");
            return "1";
        }
    }
}
